using System;

namespace AGame.TabOrm.TabOrmAttributeExpand
{
    public class ExtRefTabField : TabField
    {
        private readonly Type _keyType;
        public string Separator;

        public ExtRefTabField(Type keyType)
        {
            _keyType = keyType;
        }
        
        public ExtRefTabField(string name, Type keyType) : base(name)
        {
            _keyType = keyType;
        }
        
        public override Func<string, object> GetStrToObjFunc(Type tabType, Type targetType)
        {
            var repository = TabOrmManager.Instance.GetRepository(targetType, _keyType);
            var methodInfo = targetType.GetMethod("GetDataById");
            if (methodInfo == null)
            {
                return null;
            }
            var keyFunc = TabOrmObjConvert.CommonConvert.GetStringToObjFunc(_keyType);
            if (keyFunc == null)
            {
                return null;
            }
            if (string.IsNullOrEmpty(Separator))
            {
                return s =>
                {
                    var key = keyFunc(s);
                    return methodInfo.Invoke(repository, new[] {key});
                };
            }
            return default;
        }

        public override Func<object, string> GetObjToStrFunc(Type tabType, Type targetType)
        {
            var repository = TabOrmManager.Instance.GetRepository(targetType, _keyType);
            var methodInfo = targetType.GetMethod("GetDataId");
            if (methodInfo == null)
            {
                return null;
            }
            var keyFunc = TabOrmObjConvert.CommonConvert.GetObjToStringFunc(_keyType);
            if (keyFunc == null)
            {
                return null;
            }

            if (string.IsNullOrEmpty(Separator))
            {
                return obj =>
                {
                    var invoke = methodInfo.Invoke(obj,new []{obj}) as Array;
                    if (invoke == null || invoke.Length == 0)
                    {
                        return null;
                    }
                    return keyFunc(invoke.GetValue(0));
                };
            }

            return default;

        }
    }
}